#include "ChunkFileReader.h"

ChunkFileReader::ChunkFileReader(QObject *parent)
    : QObject(parent)
{

}

bool ChunkFileReader::start(const QString &filePath, qint64 chunkSize)
{
    m_chunkSize = chunkSize;
    m_file.setFileName(filePath);
    if (!m_file.open(QIODevice::ReadOnly)) {
        qWarning() << "无法打开文件:" << m_file.errorString();
        return false;
    }

    m_totalSize = m_file.size();
    m_bytesSent = 0;

    // 使用定时器避免阻塞事件循环（可选）
    sendNextChunk();
    return true;
}

void ChunkFileReader::sendNextChunk()
{
    if (m_file.atEnd()) {
        emit finished();
        m_file.close();
        return;
    }

    QByteArray chunk = m_file.read(m_chunkSize);
    if (chunk.isEmpty()) {
        qDebug() << QStringLiteral("读取失败或文件结束!");
        emit finished();
        m_file.close();
        return;
    }

    m_bytesSent += chunk.size();
    emit chunkReady(chunk);
    emit progress(m_bytesSent, m_totalSize);

    // 继续下一块（非阻塞方式）
    QTimer::singleShot(1, this, &ChunkFileReader::sendNextChunk);
}
